//
//  StrategyNearbyPhotoViewController.m
//  ITrip
//
//  Created by dllo on 15/6/1.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "StrategyNearbyPhotoViewController.h"

@interface StrategyNearbyPhotoViewController ()<UIAlertViewDelegate>

{
    UIActivityIndicatorView *activityIndicator;
    UICollectionViewFlowLayout *layout;
}
@end

@implementation StrategyNearbyPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImage *icon = [UIImage imageNamed:@"iconfont_return"];
    icon = [icon imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStyleDone target:self action:@selector(getBack)];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    title.text = self.titleName;
    title.font = [UIFont systemFontOfSize:20];
    title.font = [UIFont boldSystemFontOfSize:25];
    title.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = title;
    
    // 定义菊花控件
    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
//    [activityIndicator release];
    [activityIndicator startAnimating];
    

    
    self.arrayData = [NSMutableArray array];
    
    NSString *path = [URLPath strategyNearbyPhotoURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *string = [path stringByAppendingFormat:@"%ld/photos.json?per_page=20&page=1", self.numberid];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *params = nil;
    
    [manager GET:string parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [activityIndicator stopAnimating];
        self.arrayData = [StrategyNearbyPhotoParser getParser:operation.responseData];
        [self createMyView];
//        NSLog(@"%ld", self.arrayData.count);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
        [activityIndicator stopAnimating];
    }];
}

- (void)getBack
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // 定义菊花控件
    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    
    [activityIndicator startAnimating];

    NSString *path = [URLPath strategyNearbyPhotoURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *string = [path stringByAppendingFormat:@"%ld/photos.json?per_page=20&page=1", self.numberid];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *params = nil;
    
    [manager GET:string parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [activityIndicator stopAnimating];
        self.arrayData = [StrategyNearbyPhotoParser getParser:operation.responseData];
        [self createMyView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
        [activityIndicator stopAnimating];
    }];
}

//
- (void)createMyView
{
    static NSInteger num = 2;
    layout = [[UICollectionViewFlowLayout alloc] init];
//    layout.itemSize = CGSizeMake((self.view.frame.size.width - 30) / 2, 200);
//    layout.minimumInteritemSpacing = 10;
//    layout.minimumLineSpacing = 10;
    
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.myNearbyPhoto = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:layout];
    self.myNearbyPhoto.delegate = self;
    self.myNearbyPhoto.dataSource = self;
    self.myNearbyPhoto.backgroundColor = [UIColor whiteColor];
    
    [self.myNearbyPhoto registerClass:[StrategyNearbyPhotoCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:self.myNearbyPhoto];
    
    [self.myNearbyPhoto addLegendFooterWithRefreshingBlock:^{
        NSString *path = [URLPath strategyNearbyPhotoURL];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *string = [path stringByAppendingFormat:@"%ld/photos.json?per_page=20&page=%ld", self.numberid, num++];
        
//        NSLog(@"%@", string);
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSDictionary *params = nil;
        
        [manager GET:string parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            [self.arrayData addObjectsFromArray:[StrategyNearbyPhotoParser getParser:operation.responseData]];
            [self.myNearbyPhoto.footer endRefreshing];
            [self.myNearbyPhoto reloadData];
//            NSLog(@"%ld", self.arrayData.count);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
            [activityIndicator stopAnimating];

        }];
    }];
    
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height;
    StrategyNearbyPhotoModel *model = [self.arrayData objectAtIndex:indexPath.row];
    if (model.photo_image_url != nil && ![model.photo_image_url isEqual:[NSNull null]]) {
        height = (self.view.frame.size.width - 30) / 2 * (model.photo_image_height / (CGFloat)model.photo_image_width);
        
    }
    return CGSizeMake((self.view.frame.size.width - 30) / 2, height);
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    StrategyNearbyPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    StrategyNearbyPhotoModel *model = [self.arrayData objectAtIndex:indexPath.row];
    cell.backgroundColor = [UIColor whiteColor];
    [cell setPhotomodel:model];
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arrayData.count;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
